<?php

namespace App\Models;

//use Illuminate\Database\Eloquent\SoftDeletes;

class AdminMenu extends Base
{
    //use SoftDeletes;

    protected $table = 'admin_menu';

//    protected $fillable = [
//        'id', 'created_id', 'created_at', 'updated_id', 'updated_at', 'deleted_id', 'deleted_at', 'parent_id', 'name', 'icon', 'sorting', 'status'
//    ];

    protected $guarded = []; // 不可以注入数据字段

    /**
     * 按父ID查找菜单子项
     *
     * @param int $parentId 父节点ID
     * @return array
     */
    public static function adminMenu($parentId)
    {
        $menus = AdminMenu::where(['parent_id' => $parentId, ['type', '<>', 3], ['status', '=', 1]])->orderBy('sorting', 'ASC')->get()->toArray();

        return $menus;
    }

    // 取得树形结构的菜单
    public static function getTree($myId, $parent = '', $level = 1)
    {
        $data = self::adminMenu($myId);
        $level++;

        if (is_array($data)) {
            $result = null;
            foreach ($data as $item) {
                $id = $item['id'];
                $name = $item['name'];
                $menu = [
                    'app' => $item['app'],
                    'controller' => $item['controller'],
                    'action' => $item['action'],
                    'route' => $item['route'],
                    'icon' => $item['icon'],
                    'id' => $id,
                    'name' => $item['name'],
                    'target' => $item['target'],
                    'type' => $item['type'],
                    'parent' => $parent,
                ];

                $result[$id . $name] = $menu;
                $child = self::getTree($item['id'], $id, $level);
                // 后台管理界面只支持五层，超出的层级的不显示
                if ($child && $level <= 5) {
                    $result[$id . $name]['items'] = $child;
                }
            }

            return $result;
        }

        return false;
    }
}
